//Created in 2015.04.10 by Huangwenhan
base_api="http://openwsn.tongji.edu.cn/site/mvc/"

window.FileModel = Backbone.Model.extend({
	urlRoot :base_api + "fdb/algorithmfiles",

	defauls:{
		"id" : "",
	},

	initialize : function() {
		this.bind('validate', function(model, error) {
			alert(error);
		});
	},

	validate : function(attributes) {
		if(attributes.id == ''){
			return "id can't be null";
		}
	}
});


window.PageableFileCollectionModel = Backbone.PageableCollection.extend ({
	model : FileModel,
    url : base_api + "fdb/algorithmfiles",
    state : {
    	pageSize : 10
    },
    mode : "client"
});


Backbone.View.prototype.close = function () {
    console.log('Closing view ' + this);
    if (this.beforeClose) {
        this.beforeClose();
    }
    this.remove();
    this.unbind();
};


BackgridDeleteCell = Backgrid.Cell.extend({
  //  template : _.template('<button class="btn btn-danger">删除</button>'),
	template : _.template('<a id="deleteone">删除</a>'),
    events : {
        "click #deleteone" : "onDeleteRow"
    },

    onDeleteRow : function(e) {
        e.preventDefault();
        if(confirm("确定要删除吗？"))
        {
        	 this.model.set('id',this.model.get('id')+'/');
             this.model.destroy({
                 success : function(model, response) {
                     alert('File deleted successfully ' );
                 },
                 error: function(error){
                         console.log("exception encountered when delete data" );
                 }
             });
        }    
        return false;
    },
    
    render : function() {
        this.$el.html(this.template());
        this.delegateEvents();
        return this;
    }
});


BackgridDownloadCell = Backgrid.Cell.extend({
   // template : _.template('<a href="/site/mvc/fdb/algorithmfiles/<%= this.model.id %>/"  target="_blank" class="btn btn-primary">下载</a>'),
	template : _.template('<a href="/site/mvc/fdb/algorithmfiles/<%= this.model.id %>/"  target="_blank" >下载</a>'),
    events : {
        "click" : "onDownloadRow"
    },

    onDownloadRow : function(e){
    },

    render : function(){
        this.$el.html(this.template());
        this.delegateEvents();
        return this;
    }
});


BackgridColumns= [{
	name : "",
	cell : "select-row",
	headerCell : "select-all"
},{
	name : "id",
    label : "算法路径",
    editable : false,
    cell : Backgrid.StringCell.extend({
    	orderSeparator : ''
    })
},{
    name : "delete",
    label : "",
    editable : false,
    cell : BackgridDeleteCell
},{
	name : "download",
	label : "",
	editable : false,
	cell : BackgridDownloadCell
}];


window.FileCollectionView = Backbone.View.extend({
	grid : Backgrid.Grid,

	events:{
		//'click #upload' : 'onUpload',
	},

	initialize: function() {
		console.log("FileCollectionView initialized!");
		this.template = _.template($("#tpl_itemlist").html());
	},

	render: function(){
         grid = new Backgrid.Grid({
         	columns : BackgridColumns,
         	collection : this.model
         });

         $(this.el).html(this.template());

         $("#backgrid").html( grid.render().el);

      

         var paginator = new Backgrid.Extension.paginator({
         	collection: this.model
         });

         $("#backgrid").append(paginator.render().el);

         return this;
	},
    
     onUpload: function(){
    	console.log("upload the file");	
    	this.model.save(null, {
			success: function() {
				alert("save successfully!");
				app.navigate('', {trigger: true});
			},
			error: function(error){
				console.log("exception encountered when save data" );
			}
		});
    }

});



function uploadfile(){
	 document.getElementById("uploadform").method="post";
	 document.getElementById("uploadform").enctype="multipart/form-data";
	 document.getElementById("uploadform").action="/site/mvc/fdb/algorithmfiles";
	 //document.getElementById("uploadform").target="_blank"
	 document.getElementById("uploadform").submit(); 
     var newwindow=window.open('http://openwsn.tongji.edu.cn/site/p/?&p=dataanalysis/alibmaintain.html');
     //newwindow.opener.close(); 
    
	 $("itemlist").show();
}

window.FileTile = Backbone.View.extend({

    initialize: function() {
        this.template = _.template($("#tpl_filetile").html());

        this.model.fetch({
            success : function(collection,resq,options){
                console.log('FileTile fetch successfully.');
            }
        });
    },

    render:function(){
        this.$el.html(this.template());
        var view =new FileCollectionView({el:"#objecteditor", model: this.model});
        view.render();
    },
})

var fileStoreApplication = Backbone.Router.extend({
    filelist: null,
    routes : {
        '' : 'getItemList',
    },

    initialize : function(){
        filelist = new window.PageableFileCollectionModel();
    },

    showView : function(selector,view){
        $(selector).empty();
        $(selector).html(view.render().el);
        this.currentView =view;
        return view;
    },

    getItemList: function() {
        var filetile = new window.FileTile({el:"#filetile", model: filelist});
        filetile.render();
    },
})

$(document).ready(function(){
    app = new fileStoreApplication();
    app.getItemList();
});
